var urlRoot = '../model/';

var mSort = 0;
var aSort = 0;
var sSort = 0;

var inputFrame;

$(function() {

	inputFrame = new FrameItem("popHolder", frameOk);

	mSort = localStorage.getItem("mSort");
	aSort = localStorage.getItem("aSort");
	sSort = localStorage.getItem("sSort");

	if (mSort == undefined)
		mSort = 0;
	if (aSort == undefined)
		aSort = 0;
	if (sSort == undefined)
		sSort = 0;

	var sortM = parseInt(mSort / 10);
	var typeM = mSort % 10;
	$("#sortModel").val(typeM);
	if (sortM != 0)
		$("#stDown1").prop("checked", 'checked');

	var sortA = parseInt(aSort / 10);
	var typeA = aSort % 10;
	$("#sortApi").val(typeA);
	if (sortA != 0)
		$("#stDown2").prop("checked", 'checked');

	var sortS = parseInt(sSort / 10);
	var typeS = sSort % 10;
	$("#sortApp").val(typeS);
	if (sortS != 0)
		$("#stDown3").prop("checked", 'checked');

	refreshAll();	
});

function sortChange(type) {

	if (type == 1) {
		var opt = $("input:radio[name='st1']:checked").val();
		var mSortNow = $("#sortModel").val() * 1 + opt * 1;

		if (mSort != mSortNow) {
			mSort = mSortNow;
			localStorage.setItem("mSort", mSortNow);
			refreshModels();
		}
	}
	else if (type == 2) {
		var opt = $("input:radio[name='st2']:checked").val();
		var aSortNow = $("#sortApi").val() * 1 + opt * 1;

		if (aSort != aSortNow) {
			aSort = aSortNow;
			localStorage.setItem("aSort", aSortNow);
			refreshApis();
		}
	}
	else if (type == 3) {
		var opt = $("input:radio[name='st3']:checked").val();
		var sSortNow = $("#sortApp").val() * 1 + opt * 1;

		if (sSort != sSortNow) {
			sSort = sSortNow;
			localStorage.setItem("sSort", aSortNow);
			refreshApps();
		}
	}
}

var frameType = 0;
var frameParam = undefined

var modelData = {}
var apiTitles = {}
var appTitles = {}
var ctData = {}

function showFrame(type, title, info, param, value) {
	frameType = type;
	frameParam = param;

	inputFrame.show(type >= 0, title, info, value);

	/*
		$("#popFrame").css("display", "block");
	
		$("#frameShow").html(info);
		$("#frameTitle").html(title);
	
		if (value)
			$("#frameInput").val(value);
		else
			$("#frameInput").val("");
	
		if (type >= 0)
			$("#frameInput").css("display", "block");
		else
			$("#frameInput").css("display", "none");
			*/
}

function frameOk(frame) {

	if (frameType >= 0)
		doCreate(frame.getInput());
	else
		doDelete();
}

function refreshAll() {
	refreshData(0);
}

function refreshModels() {
	refreshData(1);
}

function refreshApis() {
	refreshData(2);
}

function refreshApps() {
	refreshData(3);
}

function refreshData(type) {

	var url;

	if (type == 1) {
		url = "models?mSort=" + mSort;
	}
	else if (type == 2) {
		url = "apis?aSort=" + aSort;
	}
	else if (type == 3) {
		url = "apps?sSort=" + sSort;
	}
	else
		url = "info?mSort=" + mSort + "&aSort=" + aSort + "&sSort=" + sSort;

	jQuery.ajax({
		type: 'GET',
		contentType: 'application/json',
		url: urlRoot + url,
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "获取模型信息出错")) {

				if (type == 0) {
					ctData = {};
					var ctItems = data.calltype;
					for (var i = 0; i < ctItems.length; i++) {
						var ct = ctItems[i];
						ctData[ct.id] = ct.title;
					}
				}

				if (type == 1 || type == 0)
					updateModels(data.models);
				if (type == 2 || type == 0)
					updateApis(data.apis);
				if (type == 3 || type == 0)
					updateApps(data.apps);
			}

			if (data.info)
				log(data.info);
		},
		error: function(e) {
			log("返回结果出错： " + JSON.stringify(e));
		}
	});
}

function updateModels(models) {
	modelData = {}
	var modelStr = "";
	for (var i = 0; i < models.length; i++) {
		var model = models[i];
		modelData[model.id] = model;
		modelStr += makeModel(model);
	}
	$("#modelList").html(modelStr);
}

function updateApis(apis) {
	apiTitles = {}
	var apiStr = "";
	for (var i = 0; i < apis.length; i++) {
		var api = apis[i];
		apiTitles[api.id] = api.title;
		apiStr += makeApi(api);
	}
	$("#apiList").html(apiStr);
}

function updateApps(apps) {
	appTitles = {}
	var appStr = "";
	for (var i = 0; i < apps.length; i++) {
		var app = apps[i];
		appTitles[app.id] = app.title;
		appStr += makeApp(app);
	}
	$("#appList").html(appStr);
}

function makeModel(data) {
	var id = data.id;

	var head = data.title + " [" + ctData[data.type] + "] " + data.url;

	modelData[id] = data.title;

	var str = "<tr><td style='text-align: left'>" + id + "</td>";

	str += "<td style='text-align: left'>" + head + "</td>";

	str += "<td style='text-align: center;'>";
	str += "<button class='btn btn32 btn-study' onclick='editModel(event, " + id + ")'></button>";
	str += "</td>";

	str += "<td style='text-align: center;'>";
	str += "<button class='btn btn32 btn-file' onclick='copyModel(" + id + ")'></button>";
	str += "</td>";

	str += "<td style='text-align: center;'>";
	str += "<button class='btn btn32 btn-del' onclick='delModel(" + id + ",\"" + head + "\")'></button>";
	str += "</td></tr>";
	return str;
}

function makeApi(data) {
	var id = data.id;
	var head = data.title;
	var model = data.modelid;

	apiTitles[id] = data.title;

	var str = "<tr><td style='text-align: left'>" + head + "</td>";

	str += "<td style='text-align: left'>" + model + "</td>";

	str += "<td style='text-align: center;'>";
	str += "<button class='btn btn32 btn-study' onclick='editApi(event, " + id + ")'></button>";
	str += "</td>";

	str += "<td style='text-align: center;'>";
	str += "<button class='btn btn32 btn-file' onclick='copyApi(" + id + ")'></button>";
	str += "</td>";

	str += "<td style='text-align: center;'>";
	str += "<button class='btn btn32 btn-del' onclick='delApi(" + id + ",\"" + head + "\")'></button>";
	str += "</td></tr>";
	return str;
}

function makeApp(data) {
	var id = data.id;
	var head = data.title;

	appTitles[id] = data.title;

	var str = "<tr><td style='text-align: left'>" + head + "</td>";

	str += "<td style='text-align: center;'>";
	str += "<button class='btn btn32 btn-study' onclick='editApp(" + id + ")'></button>";
	str += "</td>";

	str += "<td style='text-align: center;'>";
	str += "<button class='btn btn32 btn-file' onclick='copyApp(" + id + ")'></button>";
	str += "</td>";

	str += "<td style='text-align: center;'>";
	str += "<button class='btn btn32 btn-del' onclick='delApp(" + id + ",\"" + head + "\")'></button>";
	str += "</td></tr>";
	return str;
}

function addModel() {
	showFrame(1, '创建新的模型', '输入新模型的名称');
}

function copyModel(id) {
	var input = modelData[id];

	if (input && input.length > 0)
		input += " (copy)";

	showFrame(11, '另存为新的模型', '输入新模型的名称', id, input);
}

function editModel(event, id) {

	var url = "./model.html?id=" + id;

	if (event && event.ctrlKey && event.type === 'click') {
		window.open(url, '_blank');
	}
	else
		toPage(url);
}

function delModel(id, head) {

	showFrame(-1, '删除模型', '确认是否删除模型: ' + head, id);
}

function addApi() {
	showFrame(2, '创建新的API', '输入新API的名称');
}

function copyApi(id) {
	var input = apiTitles[id];

	if (input && input.length > 0)
		input += " (copy)";

	showFrame(12, '另存为新的API', '输入新API的名称', id, input);
}

function editApi(event, id) {
	var url = "./api.html?id=" + id;

	if (event && event.ctrlKey && event.type === 'click') {
		window.open(url, '_blank');
	}
	else
		toPage(url);
}

function delApi(id, head) {
	showFrame(-2, '删除API', '确认是否删除API: ' + head, id);
}

function addApp() {
	showFrame(3, '创建新的应用', '输入新应用的名称');
}

function copyApp(id) {
	var input = appTitles[id];

	if (input && input.length > 0)
		input += " (copy)";

	showFrame(13, '另存为新的应用', '输入新应用的名称', id, input);
}

function editApp(id) {
	toPage("./app.html?id=" + id);
}

function delApp(id, head) {

	showFrame(-1, '删除应用', '确认是否删除应用: ' + head, id);
}

function doCreate(title) {

	if (!title || title.length == 0) {
		logTo('名称不能为空', 'infoout2');
		return;
	}

	var method;
	if (frameType == 1) {
		method = "createmodel";
	}
	else if (frameType == 11) {
		method = "copymodel";
	}
	else if (frameType == 2) {
		method = "createapi";
	}
	else if (frameType == 12) {
		method = "copyapi";
	}
	else if (frameType == 3) {
		method = "createapp";
	}
	else if (frameType == 13) {
		method = "copyapp";
	}

	var param = {}
	param.title = title;

	if (frameType < 10)
		param.source = -1;
	else
		param.source = frameParam;

	jQuery.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: urlRoot + method,
		data: JSON.stringify(param),
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, "提交创建信息失败", undefined, 'infoout2')) {

				var id = data.id;
				var tType = frameType % 10;
				if (tType == 1)
					editModel(undefined, id);
				else if (tType == 2)
					editApi(undefined, id);
				else if (tType == 3)
					editApp(id);

				inputFrame.hide();
			}
		},
		error: function(e) {
			showAjaxError(e);
		}
	});
}
function doDelete() {

	var method;
	var errTitle;

	if (frameType == -1) {
		method = 'delmodel?id=';
		errTitle = "删除模型信息出错";
	}
	else if (frameType == -2) {
		method = 'delapi?id=';
		errTitle = "删除API信息出错";
	}
	else if (frameType == -3) {
		method = 'delapp?id=';
		errTitle = "删除APP信息出错";
	}

	var id = frameParam;

	jQuery.ajax({
		type: 'GET',
		contentType: 'application/json',
		url: urlRoot + method + id,
		dataType: 'json',
		async: false,
		success: function(data) {
			if (checkApiErrorInfo(data, errTitle)) {
				if (frameType == -1)
					refreshModels();
				else if (frameType == -2)
					refreshApis();
				else
					refreshApps();
			}

			if (data.info)
				log(data.info);

			inputFrame.hide();
		},
		error: function(e) {
			log("返回结果出错： " + JSON.stringify(e));
		}
	});
}